<?php
/**
 * Author:JunSong
 * CreatedTime: 2021/4/2 18:13
 */


class GetFileDir {
    private $_dir;
    private $_emptyDir;
    private $_fileType;
    public $_files;

    public function __construct($_dir,$_emptyDir = false,$_fileType = false) {
        $this->_dir = $_dir;
        $this->_emptyDir = $_emptyDir;
        $this->_fileType = $_fileType;
        if ($this->_emptyDir) {
            $this->getFileEmpty($this->_dir,$this->_files);
        } else {
            $this->getFile($this->_dir,$this->_files);
        }
    }
    //读取文件夹所有文件不包括空文件夹
    private function getFile($_dir,&$_arr) {

        if (!!$_dirs = opendir($_dir)) {
            while (($_file=readdir($_dirs)) != false) {
                if ($_file == '.' || $_file == '..') continue;
                $_files = $_dir .'/'. $_file;

                if (is_dir($_files)) {
                    $this->getFile($_files,$_arr);
                } else {
                    if ($this->_fileType) {
                        $_arr[] = $_files;
                    } else {
                        $_arr[] = $_files;
                    }
                }
            }
        }
        closedir($_dirs);
    }
    //读取文件夹所有文件包括空文件夹
    private function getFileEmpty($_dir,&$_arr) {
        if (!!$_dirs = opendir($_dir)) {
            while (($_file=readdir($_dirs)) != false) {
                if ($_file == '.' || $_file == '..') continue;
                $_files = $_dir .'/'. $_file;
                if (is_dir($_files) && $this->isEmpty($_files)) {
                    $this->getFileEmpty($_files,$_arr);
                } else {
                    if ($this->_fileType) {
                        $_arr[] = $_files;
                    } else {
                        $_arr[] = $_files;
                    }
                }
            }
        }
        closedir($_dirs);
    }
    //判断文件夹是否为空
    private function isEmpty($_dir) {
        if (!!$_dirs = opendir($_dir)) {
            while (($_file=readdir($_dirs)) != false) {
                if($_file != '.' && $_file != '..') {
                    closedir($_dirs);
                    return true;
                    break;
                }
            }
            closedir($_dirs);
            return false;
        }
    }
}
